package tech.mhuang.pacebox.springboot.autoconfiguration.cors;

import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.autoconfigure.condition.ConditionalOnWebApplication;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;
import tech.mhuang.pacebox.springboot.autoconfiguration.ConfigConsts;

import java.util.Arrays;

/**
 * cors import
 *
 * @author mhuang
 * @since 2020.0.0.2
 */
@Configuration
@EnableConfigurationProperties(value = CorsProperties.class)
@ConditionalOnWebApplication(type = ConditionalOnWebApplication.Type.SERVLET)
@ConditionalOnProperty(prefix = ConfigConsts.CORS, name = ConfigConsts.ENABLE, havingValue = ConfigConsts.TRUE)
public class InterCorsAutoConfiguration {

    private final CorsProperties properties;

    public InterCorsAutoConfiguration(CorsProperties properties) {
        this.properties = properties;
    }

    @Bean
    @Order(Integer.MIN_VALUE)
    public CorsFilter corsFilter() {
        UrlBasedCorsConfigurationSource urlBasedCorsConfigurationSource = new UrlBasedCorsConfigurationSource();
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        corsConfiguration.setAllowCredentials(properties.isAllowCredentials());
        corsConfiguration.setAllowedOriginPatterns(Arrays.asList(properties.getAllowedOriginPatterns()));
        corsConfiguration.setAllowedHeaders(Arrays.asList(properties.getHeaders()));
        corsConfiguration.setAllowedMethods(Arrays.asList(properties.getMethods()));
        corsConfiguration.setMaxAge(properties.getMaxAge());
        urlBasedCorsConfigurationSource.registerCorsConfiguration(properties.getMappings(), corsConfiguration);
        return new CorsFilter(urlBasedCorsConfigurationSource);
    }
}
